<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="60%" >
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">
      <!-- 第一行：车辆名称、维修地点 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="车辆名称" prop="vehicleName">
            <el-select v-model="formData.vehicleName" placeholder="请选择" filterable>
              <el-option v-for="vehicle in vehicleList" :key="vehicle.id" :label="vehicle.vehicleName"
                         :value="vehicle.vehicleName" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="维修地点" prop="repairLocation">
            <el-input v-model="formData.repairLocation" placeholder="请完善维修地点" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行：维修日期、维修费用 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="维修日期" prop="repairDate">
            <el-date-picker v-model="formData.repairDate" type="date" value-format="x" placeholder="请选择维修日期" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="维修费用" prop="repairCost">
            <el-input v-model="formData.repairCost" placeholder="请输入维修费用" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行：相关附件、经手人 -->
      <el-row :gutter="20">

        <el-col :span="12">
          <el-form-item label="经手人" prop="nickName">
            <!--            <el-select v-model="formData.handlerId" placeholder="请选择">-->
            <!--              <el-option-->
            <!--                v-for="user in users"-->
            <!--                :key="user.id"-->
            <!--                :label="user.nickname"-->
            <!--                :value="user.nickname"-->
            <!--              />-->
            <!--            </el-select>-->

            <UserSelect @node-change="handleNodeChange" v-model="formData.nickName" />

          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行：维修内容 -->
      <el-form-item label="维修内容" prop="repairContent">
        <!--        <Editor v-model="formData.repairContent" height="150px" />-->
        <el-input v-model="formData.repairContent" style="width: 100%;" :rows="4" type="textarea"
                  placeholder="请输入维修内容" />
      </el-form-item>
      <!-- 相关附件 -->
      <el-col :span="24">
        <el-form-item label="相关附件" >
          <OaFileManager :folderDisabled="true" :initial-file-ids="formData.files" @fileSelectSuccess="fileSelectScccess"  />
        </el-form-item>
      </el-col>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { VehicleRepairApi, VehicleRepairVO } from '@/api/oa/vehiclerepair'
import { ref, watch, defineExpose, defineProps } from 'vue'
import UserSelect from '@/views/system/user/UserSelect.vue'
import { useVehicleList } from '@/hooks/web/useVehicleList'
import { VehicleApi } from '@/api/oa/vehicle'

/** 车辆维修记录 表单 */
defineOptions({ name: 'VehicleRepairForm' })

const { vehicleList, loadVehicleList, updateLicensePlate } = useVehicleList()
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const licensePlateRef = ref<string | undefined>(undefined)
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  vehicleName: undefined,
  licensePlate: undefined as string | undefined,
  repairDate: undefined,
  repairCost: undefined,
  repairContent: undefined,
  repairLocation: undefined,
  handlerId: undefined,
  nickName: undefined
})
const formRules = reactive({
  vehicleName: [{ required: true, message: '车辆名称不能为空', trigger: 'blur' }],
  licensePlate: [{ required: true, message: '车辆号码不能为空', trigger: 'blur' }],
  repairDate: [{ required: true, message: '维修日期不能为空', trigger: 'blur' }],
  repairCost: [{ required: true, message: '维修费用(元)不能为空', trigger: 'blur' }],
  repairContent: [{ required: true, message: '维修内容不能为空', trigger: 'blur' }],
  repairLocation: [{ required: true, message: '维修地点不能为空', trigger: 'blur' }],
  handlerId: [{ required: true, message: '经手人不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const props = defineProps({
  vehicleId: {
    type: [Number, String],
    required: true
  }
})

watch(
  () => formData.value.vehicleName,
  (newVal) => {
    updateLicensePlate(newVal, licensePlateRef)
  }
)

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await VehicleRepairApi.getVehicleRepair(id)
    } finally {
      formLoading.value = false
    }
  }
  else {
    // 新增模式下，尝试填充车辆信息
    if (props.vehicleId) {
      try {
        const rowData = await VehicleApi.getVehicle(props.vehicleId)
        formData.value.vehicleName = rowData.name
        licensePlateRef.value = rowData.licensePlate
      } catch (err) {
        message.warning('无法自动填充车辆信息')
      }
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗



/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  formData.value.licensePlate = licensePlateRef.value
  // 提交请求
  formLoading.value = true
  try {

    const data = formData.value as unknown as VehicleRepairVO

    if (formType.value === 'create') {
      await VehicleRepairApi.createVehicleRepair(data)
      message.success(t('common.createSuccess'))
    } else {
      await VehicleRepairApi.updateVehicleRepair(data)
      message.success(t('common.updateSuccess'))
    }

    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}




/** 重置表单 */
const resetForm = () => {
  formData.value = {
    vehicleName: undefined,
    licensePlate: undefined,
    repairDate: undefined,
    repairCost: undefined,
    repairContent: undefined,
    repairLocation: undefined,
    handlerId: undefined,
    nickName: undefined
  }
  formRef.value?.resetFields()
}

/** 员工被点击事件 */
const handleNodeChange = async (row) => {
  formData.value.handlerId = row.id
  formData.value.nickName = row.nickname
}
const fileSelectScccess = (fileIds: string[]) => {
  formData.value.files = fileIds.join(',')
}
onMounted(() => {
  loadVehicleList()
})
</script>
